import os
import cv2
import numpy as np
import pyautogui
import time
import platform

from datetime import datetime
import mss

class SmartAutoClicker:
    def __init__(self):
        pyautogui.FAILSAFE = True
        pyautogui.PAUSE = 0.1
        
        # 初始化mss截图器
        self.sct = mss.mss()
        
        # 图片缓存
        self.image_cache = {}
        
        # 修复macOS高分屏坐标偏移
        self.scale_factor = 2 if self.fast_screenshot().shape[1] > pyautogui.size()[0] else 1

        self.system = platform.system()
        
        # 获取当前脚本所在目录
        current_dir = os.path.dirname(os.path.abspath(__file__))
        liupai_dir = os.path.join(current_dir, 'liupai')
        
        self.button_configs_windows = [
            (os.path.join(liupai_dir, "确定按钮.png"), "确定", 0.65),
            (os.path.join(liupai_dir, "开始挑战按钮.png"), "开始挑战", 0.65),
            (os.path.join(liupai_dir, "选择作战队长按钮(点击文字{战士}).png"), "选择队长", 0.65),
            (os.path.join(liupai_dir, "结束的确定按钮.png"), "结束的确定按钮", 0.65)
        ]

        self.button_configs_mac = [
            (os.path.join(liupai_dir, "确定按钮-mac.png"), "确定-mac", 0.65),
            (os.path.join(liupai_dir, "选择队长-mac.png"), "选择队长-mac", 0.65),
            (os.path.join(liupai_dir, "开始挑战按钮-mac.png"), "开始挑战-mac", 0.65),
            (os.path.join(liupai_dir, "结束的确认按钮-mac.png"), "结束的确定按钮-mac", 0.65)
        ]
        self.check_interval = 0.5  # 检测间隔(秒)
        
    def log(self, message):
        """打印带时间戳的日志"""
        print(f"[{datetime.now().strftime('%H:%M:%S')}] {message}")
    
    def load_image(self, filepath):
        """安全加载图片，带缓存"""
        if filepath in self.image_cache:
            return self.image_cache[filepath]
            
        try:
            data = np.fromfile(filepath, dtype=np.uint8)
            img = cv2.imdecode(data, cv2.IMREAD_COLOR)
            if img is not None:
                self.image_cache[filepath] = img
            return img
        except Exception as e:
            self.log(f"加载图片失败 {filepath}: {e}")
            return None

    def fast_screenshot(self):
        """使用mss进行快速截图"""
        try:
            img = self.sct.grab(self.sct.monitors[0])
            return np.array(img)[:, :, :3]  # 去掉alpha通道
        except Exception as e:
            self.log(f"mss截图失败，使用pyautogui: {e}")
            screenshot = pyautogui.screenshot()
            return cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
    
    def find_button(self, template_path, confidence=0.7):
        """查找按钮位置"""
        template = self.load_image(template_path)
        if template is None:
            return None
            
        try:
            screenshot = self.fast_screenshot()
            
            result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
            _, max_val, _, max_loc = cv2.minMaxLoc(result)
            
            if max_val >= confidence:
                h, w = template.shape[:2]
                center = (max_loc[0] + w//2, max_loc[1] + h//2)
                return center, max_val
            
            return None, max_val
            
        except Exception as e:
            self.log(f"查找按钮失败: {e}")
            return None, 0
    
    def wait_for_button(self, template_path, name, confidence=0.7):
        """死等按钮出现，不超时"""
        self.log(f"等待 {name} 按钮出现...")
        
        attempts = 0
        while True:
            pos, conf = self.find_button(template_path, confidence)
            if pos:
                self.log(f"找到 {name} 按钮: {pos} (置信度: {conf:.2f})")
                return pos
            
            attempts += 1
            if attempts % 10 == 0:  # 每5秒提醒一次
                self.log(f"还在等 {name} 按钮...")
            
            time.sleep(0.5)
    
    def click_button(self, pos, name):
        """点击按钮（修复高分屏坐标偏移）"""
        try:
            # 修复macOS高分屏坐标偏移
            fixed_pos = (int(pos[0] / self.scale_factor), int(pos[1] / self.scale_factor))
            pyautogui.click(fixed_pos)
            self.log(f"点击 {name}: {fixed_pos} (原始坐标: {pos}, 缩放因子: {self.scale_factor})")
            return True
        except pyautogui.FailSafeException:
            self.log("紧急停止！鼠标移到左上角")
            return False
    
    def run_once(self):
        """智能识别：哪个按钮出现就点哪个"""
        # 根据系统过滤
        if self.system == "Darwin":  # macOS
            button_configs = self.button_configs_mac
        elif self.system == "Windows":  # Windows
            button_configs = self.button_configs_windows
        while True:
            clicked = False
            
            for template_path, name, confidence in button_configs:
                if not os.path.exists(template_path):
                    continue
                
                pos, conf = self.find_button(template_path, confidence)
                if pos and conf >= confidence:
                    self.log(f"检测到 {name} 按钮: {pos} (置信度: {conf:.2f})")
                    if not self.click_button(pos, name):
                        return False
                    clicked = True
                else:
                    self.log(f"未检测到 {name} 按钮")
                time.sleep(1)
            if not clicked:
                time.sleep(0.5)  # 没检测到任何按钮，短暂等待再扫
    
    def start_auto_mode(self):
        """开始自动模式"""
        print("=== 智能自动点击器 ===")
        print("特点：智能等待按钮出现，不固定等待时间")
        print("鼠标移到左上角停止，Ctrl+C退出")
        print("3秒后开始...")
        
        time.sleep(3)
        
        cycle = 1
        try:
            self.run_once()    
        except KeyboardInterrupt:
            self.log("\n程序退出")

if __name__ == "__main__":
    clicker = SmartAutoClicker()
    clicker.start_auto_mode()